<?php
/**
 * 数据库操作类
 * @author chenhao
 * @copyright 成都四方客信息技术有限公司
 * @link http://www.sifangke.cn/
 * @since Thu Nov 12 17:24:08 CST 2009
 */
 
 
if (!defined('IN_SYS')) {
	die('No admittance');
}

class cls_mysql {
	
	private $_dbhost;
	private $_dbuser;
	private $_dbpassword;
	private $_dbname;
	private $link = null;
	private $version = '';
	public $error_message = array();
	
	public function __construct($host, $user, $pw, $dbname, $port = '3306', $charset = 'utf8', $pconnect = 0) {
		$this->_dbhost = $host .':'. $port;
		$this->_dbuser = $user;
		$this->_dbpassword = $pw;
		$this->_dbname = $dbname;
		
		$this->connect($this->_dbhost, $this->_dbuser, $this->_dbpassword, $this->_dbname, $charset, $pconnect);
	}
	
	private function connect($host, $user, $pw, $dbname, $charset, $pconnect) {
		if ($pconnect) {
			if (!($this->link = @mysql_pconnect($host,$user,$pw))) {
				$this->ErrorMsg("Can't pconnect MYSQL server($host)!");
				return false;
			}
		}
		else {
			if (!$this->link = @mysql_connect($host, $user, $pw, true)) {
				$this->ErrorMsg("Can't connect MYSQL server($host)!");
				return false;
			}
		}
		/* 如果mysql 版本是 4.1+ 以上，需要对字符集进行初始化 */
		//$this->set_mysql_charset($charset);
		if ($this->version() > '4.1')
        {
        	$charset = strtolower(str_replace('-', '', $charset));
            if ($charset != 'latin1')
            {
                mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link);
            }
            if ($this->version() > '5.0.1')
            {
                mysql_query("SET sql_mode=''", $this->link);
            }
        }
        /* 选择数据库 */
        if ($dbname) {
        	if (mysql_select_db($dbname, $this->link) === false ) {
        		$this->ErrorMsg("Can't select MySQL database($dbname)!");
        		return false;
        	}
        	else {
        		return true;
        	}
        }
        else {
        	return true;
        }
	}
	
	public function select_database($dbname) {
		return mysql_select_db($dbname, $this->link);
	}
	
	public function set_mysql_charset($charset) {
		if ($this->version() > '4.1') {
			if (in_array(strtolower($charset),array('uft8','utf-8','gbk','gb2312','big5'))) {
				$charset = str_replace('-','',$charset);
			}
			if ($charset != 'latin1') {
				mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link);
			}
		}
	}
	
	public function fetch_array($query, $result_type = MYSQL_ASSOC) {
		return mysql_fetch_array($query, $result_type);
	}
	
	public function query($sql, $type = '') {
		if ($this->link === null) {
			$this->connect($this->_dbhost, $this->_dbuser, $this->_dbpassword, $this->_dbname);
		}
		
		if (!($query = mysql_query($sql, $this->link)) && $type != 'SILENT')
        {
            $this->error_message[]['message'] = 'MySQL Query Error';
            $this->error_message[]['sql'] = $sql;
            $this->error_message[]['error'] = mysql_error($this->link);
            $this->error_message[]['errno'] = mysql_errno($this->link);

            $this->ErrorMsg();

            return false;
        }
        return $query;
	}
	
	public function affected_rows() {
		return mysql_affected_rows($this->link);
	}
	
	public function insert_id() {
		return mysql_insert_id($this->link);
	}
	
	public function error () {
		return mysql_error($this->link);
	}
	
	public function erron() {
		return mysql_errno($this->link);
	}
	
	public function client_encoding ($query) {
		return mysql_client_encoding($this->link);
	}
	
	public function result($query, $row) {
		return mysql_result($query, $row);
	}
	
	public function num_rows($query) {
		return mysql_num_rows($query);
	}
	
	public function num_fields($query) {
		return mysql_num_fields($query);
	}
	
	public function free_result($query) {
		return mysql_free_result($query);
	}
	
	public function fetchRow($query) {
		return mysql_fetch_assoc($query);
	}
	
	public function fetch_fields($query) {
		return mysql_fetch_field();
	}
	
	public function version() {
		$this->version = mysql_get_server_info($this->link);
		return $this->version;
	}
	
	public function close() {
		return mysql_close($this->link);
	}
	
	public function ErrorMsg($message = '', $sql = '') {
		if ($message) {
			echo "<b>System info</b>:$message\n\n<br /><br />";
		}
		else {
			echo "<b>MySQL server error report:<br />";
			print_r($this->error_message);
			echo "<br /><br /><a href='http://faq.sifangke.cn/?type=mysql' target='_blank'>http://faq.sifangke.cn/</a>";
		}
		exit;
	}
	
	/*仿真ADODB函数*/
	
	/**
	 * 查询指定记录数目
	 *
	 * @param string $sql
	 * @param int $num
	 * @param int $start
	 * @return bool
	 */
	public function selectLimit($sql, $num, $start = 0) {
		if ($start == 0) {
			$sql .= ' LIMIT '.$num;
		} else {
			$sql .= ' LIMIT '.$start.', '.$num;
		}
		return $this->query($sql);
	}
	/**
	 * 以数组array($value)形式取出一条记录
	 *
	 * @param string $sql
	 * @param bloo $limited
	 * @return string
	 */
	public function getOne($sql, $limited = false) {
		if ($limited == true) {
            $sql = trim($sql . ' LIMIT 1');
        }

        $res = $this->query($sql);
        if ($res !== false) {
            $row = mysql_fetch_row($res);

            if ($row !== false) {
                return $row[0];
            } else {
                return '';
            }
        } else {
            return false;
        }
	}
	/**
	 * 以数组array($key => $value,[$key => $value])形式取出所有记录
	 *
	 * @param string $sql
	 * @return array()
	 */
	public function getAll($sql) {
		$res = $this->query($sql);
		if ($res !== false) {
			$arr = array();
			while ($row = mysql_fetch_assoc($res)) {
				$arr[] = $row;
			}
			return $arr;
		} else {
			return false;
		}
	}
	/**
	 * 以数组array($key => $value)形式取出一条记录
	 *
	 * @param string $sql
	 * @param bloo $limited
	 * @return array()
	 */
	public function getRow($sql, $limited = false) {
		if ($limited == true) {
			$sql = trim($sql.' LIMIT 1');
		}
		
		$res = $this->query($sql);
		if ($res !== false) {
			return mysql_fetch_assoc($res);
		} else {
			return false;
		}
	}
	/**
	 * 以数组array($value,[$value])形式反回所有记录
	 *
	 * @param string $sql
	 * @return array()
	 */
	public function getCol($sql) {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = array();
            while ($row = mysql_fetch_row($res)) {
                $arr[] = $row[0];
            }
            return $arr;
        } else {
            return false;
        }
    }
}
